# -*- coding:utf-8 -*-


import os
import time
import datetime
import csv
import re
from pathlib import Path
import subprocess
import random
import win32api
import shutil
import chinese_calendar



def deep_list_dir(path, saveFileName):
    items = os.scandir(path)

    for file in items:
        fileType = ""
        # 去掉.的文件夹、 .classf
        if file.name.endswith(".git") or file.name.endswith(".gitee") or file.name.endswith(".github") \
                or file.name.endswith(".idea") or file.name.endswith(".class"):
            continue
        else:
            stat = file.stat()
            if file.is_dir():
                fileType = '文件夹'
                deep_list_dir(file.path, saveFileName)
            if file.is_file():
                fileType = '文件'

            suffixName = file.name[file.name.rfind('.') + 1:]
            # 文件创建时间
            fileCreateDate = datetime.datetime.fromtimestamp(stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S')
            # 文件的最近修改时间
            fileModifyDate = datetime.datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
            print(f'类型：{fileType}')
            print(f'文件名：{file.name}')
            print(f'路径：{file.path}')
            print(f'扩展名：{suffixName}')
            print(f'文件的体积大小：{stat.st_size}')
            print(f'创建时间：{fileCreateDate}')
            print(f'文件的最近修改时间：{fileModifyDate}')
            print(f'文件的最近访问时间：{datetime.datetime.fromtimestamp(stat.st_atime).strftime('%Y-%m-%d %H:%M:%S')}')
            print("================")

            # 提取文件类型中的内容
            if fileType == '文件':
                txt = ""
                repContent = ""
                if file.name.endswith(".java"):
                    # 打开文件，提取注释时间，内容
                    with open(file.path, 'r', encoding='utf-8', errors='ignore') as f:
                        line = f.read()
                    # 提取文件开头注释整段内容
                    fileCreateDate, txt, repContent = findTimeContent(line, "")

                # 将文件类型、文件名称、文件路径、创建时间保存csv
                with open(saveFileName, 'a+', encoding="utf-8-sig", newline='') as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow([fileType, suffixName, file.name, file.path, fileCreateDate.split(' ')[0], txt,
                                         fileModifyDate])


def writeCodeFile(filePath, content):
    # 将文件类型、文件名称、文件路径、创建时间保存csv
    with open(filePath, 'w', encoding='utf-8') as file:
        file.write(content)


def set_system_time(year, month, day, hour, minute, second):
    # 将时间转换为 struct_time 对象
    # time_struct = time.struct_time((year, month, day, hour, minute, second, -1, -1, -1))
    time_cls = (year, month, day, hour, minute, second, -1, -1, -1)
    time_struct = time.localtime(time.mktime(time_cls) - 8 * 60 * 60)  # 本为东八区，却set后多出8小时 UTC多了8个小时 ， 所以……
    # 设置系统时间
    win32api.SetSystemTime(time_struct.tm_year, time_struct.tm_mon, time_struct.tm_wday, time_struct.tm_mday,
                           time_struct.tm_hour, time_struct.tm_min, time_struct.tm_sec, 0)


def create_directory_file(targetType, targetPath, content):
    '''
    创建文件夹、文件。如果目标路径不在，则创建
    :param targetType:类型
    :param targetPath:路径
    :param content:文件内容
    :return:
    '''
    file_path = Path(targetPath)
    match targetType:
        case "文件夹":
            if file_path.is_dir():
                print(f"{file_path} 存在")
            else:
                file_path.mkdir(parents=True)  # 创建目录及上级目录
                print(f"{file_path} 不存在")
        case "文件":
            if file_path.is_file():
                print(f"{file_path} 存在")
            else:
                # 解析文件所在路径，如果文件所在路径不存在，则创建后在生成文件
                pathList = targetPath.split("\\")
                pathList.pop()
                newPath = "\\".join(pathList)
                new_path = Path(newPath)
                if not new_path.is_dir():
                    new_path.mkdir(parents=True)  # 创建目录及上级目录
                # 创建文件
                writeCodeFile(targetPath, content)
                print(f"{file_path} 不存在")

def findTimeContent(sourceContent, repTime):
    """
    查找注释内容中的时间，替换作者、时间
    :param content: 源内容
    :param repTime: 替换的时间
    :return: 返回替换后 时间contentTime 内容txt 整个内容repContent
    """
    repContent = ""  # 替换后的内容
    # 提取文件开头注释整段内容
    contentTime = ""  # 提取时间
    txt = ""  # 提取注释内容
    patternAll = r"\/\*\*(.*?)\*\/"
    patternAll = r"\/\*\*.*?\*\/"
    matches = re.findall(patternAll, sourceContent, re.DOTALL)
    if matches.__len__() > 0:
        content = "".join(matches[0])
        content = sourceContent  # 临时
        # 提取时间
        patternRQ = r"(\d{4})[/|-](\d{1,2})[/|-](\d{1,2})"
        reResult = re.findall(patternRQ, content)
        if reResult.__len__() > 0:
            contentTime = "-".join(reResult[0])
            # 有时间，则替换
            if repTime != "":
                # repContent = re.sub(patternRQ, "Date: " + repTime, content)  # 将内容替换为新的时间
                repContent = re.sub(patternRQ, repTime, content)  # 将内容替换为新的时间
            else:
                repContent = content
        # 提取作者
        patternAuthor = r".*[a|A]uthor[:|\s|:\s](.*)"
        authorResult = re.findall(patternAuthor, content)
        if authorResult.__len__() > 0:
            author = authorResult[0]
            repContent = re.sub(patternAuthor, " * @Author: GuoYang", repContent)  # 将内容替换为新的作者
        # 提取注释内容
        patternTxt = re.findall(r"[\u4e00-\u9fff]+", content)
        if patternTxt.__len__() > 0:
            txt = " ".join(patternTxt)
        # 将替换好的信息返回
        # repContent = re.sub(patternAll, repContent, sourceContent)
    return contentTime, txt, repContent


if __name__ == '__main__':
    # 遍历文件夹内容提取时间、内容并保存csv
    # deep_list_dir(r'E:\Downloads\pig-jdk17', "file.csv")
    # deep_list_dir(r'E:\Downloads\zhaikucloud-jdk17', "file.csv")
    # deep_list_dir(r'E:\Downloads\koala-ui-jdk17', "file.csv")
    # deep_list_dir(r'E:\Downloads\zhaiku-ui-jdk17', "file.csv")
    # deep_list_dir(r'E:\Workspaces\wechat\xmall-wechat', "file.csv")
    deep_list_dir(r'E:\Downloads\xmall-master', "file.csv")

    # 按照csv文件生成对应文件
    with open("file-koala-ui.csv", 'r', encoding="utf-8-sig", newline='') as f:
        reader = csv.reader(f)
        # 设置时间为升序
        n_day = 0
        n_hour = 0
        n_minute = 0
        for line in reader:
            result = ""
            # 如果csv中时间列不为空，则提取年、月、日 只提取时间不为空的
            if line[4] != "":
                result = "完成"
                toTime = line[4].split('/')
                year = int(toTime[0])
                month = int(toTime[1])
                day = int(toTime[2])
                hour = random.randint(14, 17)
                minute = random.randint(0, 59)
                second = random.randint(0, 59)
                # 设置时间升序
                if day != n_day:
                    n_day = day
                    hour = random.randint(14, 17)
                    n_hour = hour
                    n_minute = minute
                else:
                    hour = random.randint(n_hour, 17)
                    minute = random.randint(n_minute, 59)
                # 判断工作日
                april_last = datetime.date(year, month, day)
                flag = chinese_calendar.is_workday(april_last)
                # 不是工作日，循环当前日期，直到是工作日的日期
                while not flag:
                    april_last = april_last + datetime.timedelta(days=1)
                    flag = chinese_calendar.is_workday(april_last)
                    year = int(workday.split('-')[0])
                    month = int(workday.split('-')[1])
                    day = int(workday.split('-')[2])
                workday = april_last.strftime("%Y-%m-%d")
                # 设置时间
                set_system_time(year, month, day, hour, minute, second)
                # 创建目标文件
                oldPath = line[3]  # 源文件路径
                targetPath = oldPath.replace("-jdk17", "")
                # 读取文件内容
                with open(oldPath, 'r', encoding='utf-8', errors='ignore') as f1:
                    fileLine = f1.read()

                # 提取java文件开头注释整段内容,并修改
                repContent = fileLine
                if line[1] == "java":
                    contentTime, txt, repContent = findTimeContent(repContent, workday)
                if line[0] == "文件":
                    # 创建文件
                    create_directory_file(line[0], targetPath, repContent)
                    # git 提交
                    subprocess.run("git add " + targetPath, shell=True)
                    subprocess.run("git commit -m " + line[5], shell=True)
            else:
                result = "未完成"

            # 将比对完成的结果保存
            with open("git完成结果.csv", 'a+', encoding="utf-8-sig", newline='') as f:
                line.append(result)
                csv_writer = csv.writer(f)
                csv_writer.writerow(line)


    # 设置时间为 2023年4月1日 12:30:00
    # set_system_time(2023, 5, 7, 12, 30, 0)
    # subprocess.run("python -V", shell=True)